package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.sys.SysMenuMapper;
import com.ysd.lis.mapper.sys.SysModuleMapper;
import com.ysd.lis.mapper.sys.SysPointsMapper;
import com.ysd.lis.request.ModulePageParam;
import com.ysd.lis.service.SysMenuService;
import com.ysd.lis.service.SysModuleService;
import com.ysd.lis.service.SysPointsService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * cold_chain.sys_module 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2023-10-18
 */
@Service
public class SysModuleServiceImpl extends ServiceImpl<SysModuleMapper, SysModule> implements SysModuleService {
    @Autowired
    SysModuleMapper sysModuleMapper;
    @Autowired
    SysMenuMapper sysMenuMapper;
    @Autowired
    SysMenuService sysMenuService;
    public  Result getPageModules(ModulePageParam modulePageParam){
        Map returnMap = new HashMap<>();
        LambdaQueryWrapper<SysModule> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<SysModule> page = new Page<SysModule>();
        page.setCurrent(modulePageParam.getPageIndex());
        page.setSize(modulePageParam.getPageSize());
        lambdaQueryWrapper.eq(SysModule ::getDelFlag, 0);
        SysUser sysUser =  RedisUserManager.getUser();
        if (StringUtils.isNotBlank(modulePageParam.getOrgId())) {
            lambdaQueryWrapper .eq(SysModule ::getOrgId, modulePageParam.getOrgId());
        } else if(StringUtils.isNotBlank(sysUser.getOrgId())){
            lambdaQueryWrapper .eq(SysModule ::getOrgId, sysUser.getOrgId());
        }
        if(StringUtils.isNotBlank(modulePageParam.getKeywords())) {
            lambdaQueryWrapper.eq(SysModule::getName, modulePageParam.getKeywords()).or().eq(SysModule::getCode, modulePageParam.getKeywords());
        }
        lambdaQueryWrapper.orderByAsc(SysModule::getSn);
        Page<SysModule>  modulePageList = sysModuleMapper.selectPage(page,lambdaQueryWrapper);
        returnMap.put("modulePageList",modulePageList);
        return Result.succ(1,"获取信息成功",returnMap);
    }

    public  Result getModuleList(String  keywords){
        Map returnMap = new HashMap<>();
        LambdaQueryWrapper<SysModule> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser =  RedisUserManager.getUser();
        if(StringUtils.isNotBlank(sysUser.getOrgId())){
            lambdaQueryWrapper.eq(SysModule ::getOrgId, sysUser.getOrgId());
        }
        if(StringUtils.isNotBlank(keywords)) {
            lambdaQueryWrapper.like(SysModule::getName, keywords).or().like(SysModule::getCode,keywords);
        }
        lambdaQueryWrapper.eq(SysModule ::getDelFlag, 0);
        lambdaQueryWrapper.orderByAsc(SysModule::getSn);
        List<SysModule>  moduleList = sysModuleMapper.selectList(lambdaQueryWrapper);
        returnMap.put("moduleList",moduleList);
        return Result.succ(1,"获取信息成功",returnMap);
    }

    public String  addModule(SysModule sysModule){
            sysModuleMapper.insert(sysModule);
             return sysModule.getId();
    }
    public Result editModule(SysModule sysModule){
        Map returnMap = new HashMap<>();
        this.baseMapper.updateById(sysModule);
        returnMap.put("module",sysModule);
        return Result.succ(1,"修改模块成功",returnMap);
    }

    public Result deleteModle(String id ){
        //删除此模块时先查看一下是否有菜单存在此模块
        LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysMenu::getModuleId,id).eq(SysMenu::getDelFlag,'0');
        Integer selectCount = sysMenuMapper.selectCount(lambdaQueryWrapper);
        if(selectCount>0){
            return Result.fail("有菜单中已经应用，请删除菜单后执行此操作");
        }else {
            SysModule sysModuleUp =  sysModuleMapper.selectById(id);
            sysModuleUp.setDelFlag(1);
            int deleteById = sysModuleMapper.updateById(sysModuleUp);
            if(deleteById>0){
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("moduleId",id);
                return  Result.succ(1,"删除成功",resultMap);
            }else{
                return Result.fail("删除失败");
            }
        }
    }

    @Autowired
    SysPointsMapper sysPointsMapper;
    @Autowired
    SysPointsService sysPointsService;
    @Override
    public Result copyModuleAndMenuByOrgId(OrganizationDTO moduleAddParam) {
        String sourceOrgId = moduleAddParam.getSourceOrgId();
        String goalOrgId = moduleAddParam.getGoalOrgId();
        Integer orgIndex = moduleAddParam.getOrgIndex();
        String s = AlphabetArray.Alphabet[orgIndex];

        sysPointsMapper.delete(new LambdaQueryWrapper<SysPoints>().eq(SysPoints::getOrgId, goalOrgId));

        List<SysPoints> sysPointsList = sysPointsMapper.selectList(new LambdaQueryWrapper<SysPoints>().eq(SysPoints::getOrgId, sourceOrgId).eq(SysPoints::getDelFlag, 0));

        List<SysPoints> addSysPointsList = new ArrayList<>();
        for (SysPoints sysPoints : sysPointsList) {
            //复制菜单
            SysPoints  sysPointAdd= new SysPoints();
            BeanUtil.copyProperties(sysPoints, sysPointAdd, "id", "orgId","moduleId");
            sysPointAdd.setOrgId(goalOrgId);

            String id = sysPoints.getId();
            String newId = s + id.substring(s.length());
            sysPointAdd.setId(newId);

            String moduleId = sysPoints.getModuleId();
            if(ToolsUtils.isNotEmpty(moduleId)){
                String newmoduleId = s + moduleId.substring(s.length());
                sysPointAdd.setModuleId(newmoduleId);
            }
            addSysPointsList.add(sysPointAdd);
        }
        sysPointsService.saveBatch(addSysPointsList);



        //根据传过来的goalOrgId删除模块和菜单
        sysModuleMapper.delete(new LambdaQueryWrapper<SysModule>().eq(SysModule::getOrgId, goalOrgId));
        sysMenuMapper.delete(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getOrgId, goalOrgId));

        //根据传过来的sourceOrgId查出所有的模块
        List<SysModule> sysModules = sysModuleMapper.selectList(new LambdaQueryWrapper<SysModule>().eq(SysModule::getOrgId, sourceOrgId).eq(SysModule::getDelFlag, 0));
        //根据传过来的sourceOrgId查出所有的菜单
        List<SysMenu> sysMenus = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getOrgId, sourceOrgId).eq(SysMenu::getDelFlag, 0));

        List<SysModule> addModuleList = new ArrayList<>();
        for (SysModule sysModule : sysModules) {
            //复制模块
            SysModule sysModuleAdd = new SysModule();
            BeanUtil.copyProperties(sysModule, sysModuleAdd, "id", "orgId");
            sysModuleAdd.setOrgId(goalOrgId);
            String id = sysModule.getId();
            String newId = s + id.substring(s.length());
            sysModuleAdd.setId(newId);
            addModuleList.add(sysModuleAdd);
        }
        this.saveBatch(addModuleList);
        List<SysMenu> addMenuList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            //复制菜单
            SysMenu sysMenuAdd = new SysMenu();
            BeanUtil.copyProperties(sysMenu, sysMenuAdd, "id", "orgId","moduleId","parentId");
            sysMenuAdd.setOrgId(goalOrgId);

            String id = sysMenu.getId();
            String newId = s + id.substring(s.length());
            sysMenuAdd.setId(newId);

            String moduleId = sysMenu.getModuleId();
            String newmoduleId = s + moduleId.substring(s.length());
            sysMenuAdd.setModuleId(newmoduleId);

            String parentId = sysMenu.getParentId();
            if(ToolsUtils.isNotEmpty(parentId)){
                String newparentId = s + parentId.substring(s.length());
                sysMenuAdd.setParentId(newparentId);
            }

            addMenuList.add(sysMenuAdd);
        }
        sysMenuService.saveBatch(addMenuList);
        return Result.succ(1,"复制成功",null);

    }

    public List<SysModule> getSysModulesByRoleId(String roleId){
        MPJLambdaWrapper<SysModule> modelsByRoleIdsWrapper = new MPJLambdaWrapper<>();
        modelsByRoleIdsWrapper
                .distinct()
                .selectAll(SysModule.class)
                .leftJoin(SysRoleModule.class, SysRoleModule::getModuleId, SysModule::getId)
                .eq(SysModule::getDelFlag, "0")
                .eq(SysRoleModule::getRoleId, roleId);
        modelsByRoleIdsWrapper.orderByAsc(SysModule::getSn);
        List<SysModule> sysModules = sysModuleMapper.selectList(modelsByRoleIdsWrapper);
        return sysModules;
    }
}
